import axios from 'axios'
import { useUserStore } from '@/stores'
import router from '@/router'

// 创建实例时配置默认值
const service = axios.create({})

// 删除参数为空的字段
const deleteEmptyAndUndefinedParams = (payload) => {
  const newObj = {};
  const objKeys = Object.keys(payload);
  objKeys.forEach(key => {
    const value = payload[key];
    if (value !== undefined && value !== null && value !== '' && !(Array.isArray(value) && value.length === 0) && !(typeof value === 'object' && Object.keys(value).length === 0)) {
      newObj[key] = value;
    }
  });
  return newObj;
}



// 请求拦截器
service.interceptors.request.use(
  async (config) => {
    const store = useUserStore()
    if (store.token) {
      config.headers.Authorization = store.token
    }
    return config
  },
  (error) => {
    return Promise.error(error)
  },
)

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    return res.data
  },
  (error) => {
    return Promise.reject(error)
  },
)

export default service
